package lsf.aHttp

import android.app.AlertDialog
import android.app.ListActivity
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.ListView
import android.widget.Toast
import com.koushikdutta.async.http.AsyncHttpClient
import com.koushikdutta.async.http.AsyncHttpGet
import com.koushikdutta.async.http.AsyncHttpResponse
import org.json.JSONObject
import java.net.URLEncoder
import android.widget.SimpleAdapter
import java.util.*
import java.io.File
import java.lang.StringBuilder


private val client = AsyncHttpClient.getDefaultInstance()

private var path = ""

class FileActivity : ListActivity() {

    private val items = ArrayList<Map<String, Any>>()

    private var myPath: String = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        myPath = path
        title = "/$path"

        client.executeJSONObject(AsyncHttpGet(root + encode(path)), object : AsyncHttpClient.JSONObjectCallback() {
            override fun onCompleted(e: Exception?, source: AsyncHttpResponse?, o: JSONObject?) {
                if (e != null) {
                    toast(e.localizedMessage)
                    return
                }

                val dirs = ArrayList<String>()
                val files = TreeMap<String, Long>()

                o!!.keys()?.forEach {
                    if (it == null) return@forEach
                    val o1 = o.getJSONObject(it)
                    if (o1.has("size")) files[it] = o1.getLong("size")
                    else dirs.add(it)
                }

                Collections.sort(dirs)

                dirs.forEach {
                    items.add(HashMap<String, Any>().apply {
                        put("type", R.drawable.folder)
                        put("name", it)
                        put("size", "")
                    })
                }

                files.forEach {
                    items.add(HashMap<String, Any>().apply {
                        put("type", R.drawable.file)
                        put("name", it.key)
                        put("size", Strs.toSize(it.value))
                    })
                }

                runOnUiThread {
                    listAdapter = SimpleAdapter(this@FileActivity, items, R.layout.item,
                            arrayOf("type", "name", "size"), intArrayOf(R.id.type, R.id.name, R.id.size))
                }
            }
        })
    }


    override fun onResume() {
        super.onResume()
        path = myPath
    }

    override fun onListItemClick(l: ListView?, v: View?, position: Int, id: Long) {
        super.onListItemClick(l, v, position, id)
        val item = items[id.toInt()]

        val name = item["name"]
        path += (if (path.equals("")) "" else "/") + name

        if (item["type"]!!.equals(R.drawable.folder)) {
            startActivity(Intent(this, this.javaClass))
            return
        }

        AlertDialog.Builder(this).setPositiveButton("下载") { _, _ ->
            client.executeFile(AsyncHttpGet(root + encode(path)), "$sd/$name", object : AsyncHttpClient.FileCallback() {
                override fun onCompleted(e: Exception?, response: AsyncHttpResponse?, result: File?) {
                    if (e != null) {
                        toast(e.localizedMessage)
                        return
                    }
                    toast("已经下载到" + result!!.absolutePath)
                }
            })
        }.show()
    }


    private fun encode(s: String?): String? {
        val a = StringBuilder()
        Strs.split(s).forEach {
            a.append("/" + URLEncoder.encode(it, "utf-8"))
        }
        return a.toString()
    }

    private fun toast(s: String?) = runOnUiThread {
        Toast.makeText(this, s, Toast.LENGTH_LONG).show()
    }
}

